<!--
 * @Author: 宋绍华
 * @Date: 2024-11-13 14:56:36
 * @LastEditors: 宋绍华
 * @LastEditTime: 2025-01-07 16:33:19
 * @FilePath: \sr_system_manager_ui\src\views\project\mine\create.vue
 * @Description: 我的项目 -- 创建项目
-->
<template>
  <div class="create-project">
    <Step :stepNum="stepNum" />
    <div class="create-project-content">
      <Edit :isProposal="isProposal" :project-id="projectId" :departmentList="departmentList" :dictList="dictList"
        :project-nature="projectNature" ref="editRef" v-if="stepNum === 0" />
      <ProjectMember :project-id="projectId" :managerName="editFormVal?.managerName" :dictList="dictList"
        ref="projectMemberRef" v-if="stepNum === 1" />
      <Cooperative :project-id="projectId" ref="cooperativeRef" v-if="stepNum === 2" />
      <ProjectBudget :projectNature="projectNature" :base-info="editFormVal" :project-id="projectId" :dictList="dictList" ref="projectBudgetRef" v-if="stepNum === 3" />
      <ProjectDoc :project-id="projectId" :dictList="dictList"  :projectNature="projectNature" ref="projectDocRef" v-if="stepNum === 4" />
      <Done :isProposal="isProposal" :project-id="projectId" ref="doneRef" v-if="stepNum === 5" @done="handleSubmit" />
    </div>
    <div class="create-project-btns">
      <el-button v-if="stepNum === 0" @click="back">取消</el-button>
      <el-button v-if="stepNum !== 0" @click="handleStep('minus')">上一步</el-button>
      <el-button @click="tempSave" v-if="stepNum !== 5">暂存</el-button>
      <el-button type="primary" :loading="loading" @click="handleStep('add')" v-if="stepNum !== 5">下一步</el-button>
      <el-button type="primary" @click="handleSubmit" v-if="stepNum === 5">提交申请</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import Step from '../components/MyProject/Step.vue';
import Edit from '../components/MyProject/Edit.vue';
import ProjectMember from '../components/MyProject/ProjectMember.vue';
import Cooperative from '../components/MyProject/Cooperative.vue';
import ProjectBudget from '../components/MyProject/ProjectBudget.vue';
import Done from '../components/MyProject/Done.vue';
import ProjectDoc from '../components/MyProject/ProjectDoc.vue';
import { getDicListApi, projectApproveSubmitApi } from '@/api/project';
import { BaseSuccessRespDTO, DictionaryListRespVO } from '@/api/project/types';
import { getDepartmentListReq as getDepartmentListReq } from '@/api/system/user';
import { DepartmentPageVO } from '@/api/system/user/type';
import { projectNatureEnum } from '@/utils/constEnum';

const { proxy } = getCurrentInstance();
const route = useRoute()
const stepNum = ref(0);
const editRef = ref() // 基本信息ref
const projectMemberRef = ref() // 项目成员ref
const cooperativeRef = ref() // 合作单位ref
const projectBudgetRef = ref() // 预算ref
const projectDocRef = ref() // 文档ref
const projectId = ref('') // 项目id
const loading = ref(false)
let timer
// 项目类型
const projectNature = computed(() => {
  return Number(route.query.projectNature || 1)
})
// 字典code 1：所属院系（部） 2：统计年度 3：一级学科 4：研究类别 5：项目分类(纵向) 6：项目分类（横向）7：项目类别 8：合作形式 9：国民经济行业 10学科分类11：合同类别（纵向） 12：合同类别（横向）13：职称 14：专业
const dictList = ref<DictionaryListRespVO[]>([])
const editFormVal = ref() // 基本信息
const departmentList = ref<DepartmentPageVO[]>() // 院/部
const isProposal = computed(() => { // 是否为立项状态
  return route.query.isProposal
})

// 获取相关字典
const { run: getDicList } = useRequest(getDicListApi, {
  manual: true,
  onSuccess: (res: DictionaryListRespVO[]) => {
    dictList.value = res
  }
})

const back = () => {
  // 关闭标签
  proxy.$tab.closePage()
}

// 创建项目
const { run: projectApproveSubmit } = useRequest(projectApproveSubmitApi, {
  manual: true,
  onSuccess: (res: BaseSuccessRespDTO) => {
    if (res.isSuccess) {
      ElMessage.success('提交成功')
      back()
    }
  }
})

const validateEdit = async (isTemp: boolean = false) => {
  switch (stepNum.value) {
    case 0: // 基本信息保存
      const val = await editRef.value?.createProject(isTemp, { id: editFormVal.value?.id })
      
      if (val) {
        editFormVal.value = val
        projectId.value = val.id
        sessionStorage.setItem('create-projectId', val.id)
      }
      return !!val
    case 1: // 项目成员保存
      return await projectMemberRef.value?.createProjectMember(isTemp)
    case 2: { // 合作单位保存
      return await cooperativeRef.value?.create(isTemp)
    }
    case 3: // 项目预算保存
      return await projectBudgetRef.value?.create(isTemp)
    case 4: // 项目文档保存
      return await projectDocRef.value?.create(isTemp)
    default:
      return true
  }
}

// 获取学院/部列表
const { run: getDepartmentList } = useRequest(getDepartmentListReq, {
  manual: true,
  onSuccess: (res: DepartmentPageVO[]) => {
    res?.forEach((item) => {
      item.title = item.departmentName
      item.value = item.departmentId
    })
    departmentList.value = res
  }
})

const handleSubmit = () => {
  // type 纵向传1，横向传2
  projectApproveSubmit({ type: isProposal.value ? 1 : projectNature.value === projectNatureEnum.projectNatureHorizontal ? 2 : 5, projectId: projectId.value })
}

// 切换步骤
const handleStep = async (type: 'add' | 'minus') => {
  if (loading.value) return
  loading.value = true
  if (type === 'add') {
    const res = await validateEdit()
    if (res) {
      stepNum.value++;
    }
  } else {
    if (stepNum.value === 0) return;
    stepNum.value--;
  }
  if (timer) clearTimeout(timer)
  timer = setTimeout(() => {
    loading.value = false
  }, 500)
}

// 暂存
const tempSave = () => {
  console.log('暂存')
  validateEdit(true)
}

onMounted(() => {
  if (sessionStorage.getItem('create-projectId') || route.query.projectId) {
    projectId.value = sessionStorage.getItem('create-projectId') || route.query.projectId
  }
  getDicList({})
  getDepartmentList()
})

onUnmounted(() => {
  sessionStorage.removeItem('create-projectId')
})
</script>
<style scoped lang='scss'>
.create-project {
  --at-apply: flex flex-col h-full;

  &-btns {
    --at-apply: flex py-16px items-center justify-center pt-20px pb-20px bg-white;
    border-top: 1px solid #E5E6EB;
  }

  &-content {
    --at-apply: flex-1 h-full bg-white  overflow-y-auto;
  }
}
</style>